package cn.js.sangu.unitStore.controller;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.common.constant.SysInfo;
import cn.js.sangu.unitStore.entity.ChatRecord;
import cn.js.sangu.unitStore.service.ChatRecordService;
import cn.js.sangu.unitStore.utils.TokenUtils;

/**
 * 聊天记录控制器
 */
@RestController
@RequestMapping("/chat")
public class ChatRecordController {

    static final String OPERATION_CHARTS = "聊天记录";

    @Resource
    private ChatRecordService chatRecordService;

    /**
     * 获取与指定用户的聊天记录
     * 
     * @param oppoId  对方用户ID
     * @param request HTTP请求（用于获取当前用户信息）
     * @return 聊天记录列表
     */
    @GetMapping("/getChatRecords")
    public R getChatRecords(String userId, String oppoId) {
        // 从请求头中获取当前用户ID（假设通过JWT token传递）
        Integer uid = Objects.requireNonNull(TokenUtils.getCurrentUser()).getId();
        if (uid == null) {
            throw new RuntimeException("用户未登录");
        }

        // 调用服务层查询聊天记录（假设按时间升序排列）
        List<ChatRecord> records = chatRecordService.getRecordByUser(uid.toString(), oppoId);
        return R.ok(records);
    }

    /**
     * 清空与指定用户的聊天记录
     * 
     * @param oppoId 对方用户ID
     * @return 操作结果
     */
    @DeleteMapping("/cleanChatRecords")
    public R cleanChatRecords(String userId, String oppoId) {
        // 从请求头中获取当前用户ID
        Integer uid = Objects.requireNonNull(TokenUtils.getCurrentUser()).getId();
        if (uid == null) {
            throw new RuntimeException("用户未登录");
        }

        // 调用服务层删除聊天记录
        chatRecordService.cleanChatRecord(uid.toString(), oppoId);
        return R.ok("聊天记录清空成功");
    }

    /**
     * 更新消息已读状态
     * 
     * @param recordId 消息记录ID
     * @return 操作结果
     */
    @PostMapping("/markAsRead")
    public R markAsRead(@RequestBody Map<String, Object> params) {
        Long recordId = Long.valueOf(params.get("recordId").toString());
        // 从请求头中获取当前用户ID
        Integer uid = Objects.requireNonNull(TokenUtils.getCurrentUser()).getId();
        if (uid == null) {
            throw new RuntimeException("用户未登录");
        }

        // 调用服务层更新已读状态
        chatRecordService.updateReadStatus(recordId, SysInfo.ReadingStatusIsConf);
        return R.ok("消息已标记为已读");
    }

}
